package com.peppa.common.grayconfig.Strategy;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.peppa.common.grayconfig.Strategy.factory.AnnoStrategy;
import com.peppa.common.grayconfig.ThreadAttributes;

import java.util.StringTokenizer;

/**
 * @author ：杜戈
 * @date ：Created in 2019-08-22 16:15
 * @description：使用请求中header的ip列表优先选择服务器
 */
@AnnoStrategy
public class HeaderIplistStrategy extends StrategyAbstract{
    private final String header_key = "ips";
    public HeaderIplistStrategy() {
        setName(H_IPS);
        setOrder(SORT_H_IPS);
    }

    @Override
    public Server getServer(ILoadBalancer balancer){
        String ips = ThreadAttributes.getHeaderValue(header_key);
        if (ips == null || ips.equals("")){
            logger.info("HTTP header ips:---null!!!");
            return null;
        }
        logger.info("HTTP header ips:---{}",ips);
        StringTokenizer stringTokenizer = new StringTokenizer(ips,DELIM_ITEM);
        while (stringTokenizer.hasMoreTokens()) {
            String ip = stringTokenizer.nextToken().trim();
            Server retserver = getIpSameServer(ip,balancer);
            if (retserver!=null){
                return retserver;
            }
        }
        return null;
    }
    @Override
    public String getName(){
        return name;
    }
}
